package com.yangmao.mvc.controller;

import com.github.pagehelper.PageInfo;
import com.yangmao.entity.Diseases;
import com.yangmao.service.api.DiseasesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author ‘洋毛’
 * @version 1.0
 * @description: TODO
 * @date 2022/1/11 16:41
 */
@Controller
public class DiseasesController {
    @Autowired
    private com.yangmao.service.api.DiseasesService DiseasesService;

    @GetMapping("/diseases/all.json")
    public ModelAndView getAllDiseases(@RequestParam(name="page",required = true,defaultValue = "1") Integer page,
                                       @RequestParam(name="size",required = true,defaultValue = "4")Integer size) {
        ModelAndView mv = new ModelAndView();

        List<Diseases> Diseases = DiseasesService.getAllDiseases(page,size);

        PageInfo pageInfo = new PageInfo(Diseases);

        mv.addObject("pageInfo", pageInfo);
        mv.setViewName("diseases_list");

        return mv;
    }

    @RequestMapping("/diseases/edit.html")
    public ModelAndView editDiseases(@RequestParam("id") String id, HttpServletRequest request) {
        ModelAndView mv = new ModelAndView();
        Diseases Diseases = DiseasesService.getDiseasesById(id);
        mv.addObject("diseases", Diseases);
        mv.setViewName("diseases_edit");

        return mv;
    }

    @PostMapping("/diseases/update.html")
    public String updateDiseases(Diseases Diseases) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = new Date();
        String str = simpleDateFormat.format(d); //将日期转换为字符串且格式按照之前制定的

        Diseases.setUpdate_time(str);
        DiseasesService.updateDiseases(Diseases);
        return "redirect:/diseases/all.json";
    }

    @RequestMapping("/diseases/delete.html")
    public String deleteDiseases(@RequestParam("id") String id) {
        DiseasesService.deleteDiseases(id);
        return "redirect:/diseases/all.json";
    }

    @PostMapping("/diseases/add.html")
    public String addDiseases(Diseases Diseases){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = new Date();
        String str = simpleDateFormat.format(d); //将日期转换为字符串且格式按照之前制定的

        Diseases.setCreate_time(str);
        Diseases.setUpdate_time(str);

        DiseasesService.addDiseases(Diseases);

        return "redirect:/diseases/all.json";
    }
}
